package com.google.code.opengw.http;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class SocketFactory {
	private static SocketFactory socketFactory;
	private SSLSocketFactory sslSocketFactory;
	static{
		try{
			socketFactory = new SocketFactory();
		} catch (Exception e) {
			
			System.exit(1);
		}
	}
	private SocketFactory() throws NoSuchAlgorithmException, KeyManagementException{
		SSLContext sc = SSLContext.getInstance("SSL");
		TrustManager[] trustManager = new TrustManager[] { new LocalTrustManager() };
		sc.init(null, trustManager, new java.security.SecureRandom());
		sslSocketFactory = sc.getSocketFactory();
	}
	public static SocketFactory getInstance(){
		return socketFactory;
	}
	
	public Socket createSocket(boolean secure) throws UnknownHostException, IOException{
		if(secure) {
			return sslSocketFactory.createSocket();
		} else {
			return new Socket();
		}
	}
	
	class LocalTrustManager implements X509TrustManager {

		@Override
		public void checkClientTrusted(X509Certificate[] certArr,
				String authType) throws CertificateException {
		}

		@Override
		public void checkServerTrusted(X509Certificate[] certArr,
				String authType) throws CertificateException {
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}

	}
}
